<template>
  <div class="app-container supplierInfo">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['console:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['console:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['console:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['console:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column label="供应商图片" align="center" prop="supplierPic" >
        <template slot-scope="scope">
            <el-image :src="scope.row.supplierPic" :preview-src-list="[scope.row.supplierPic]" style="width: 50px;max-height: 150px;"/>
          </template>
      </el-table-column>
      <el-table-column label="供应商评分" align="center" prop="score" />
      <el-table-column label="供应商类别" align="center" prop="serviceId" >
        <template slot-scope="scope">
          {{serviceMap[scope.row.serviceId]}}
        </template>
      </el-table-column>
      <el-table-column label="供应商详细地址" align="center" prop="supplierDetailAddress" />
      <el-table-column label="供应商详情" align="center" prop="supplierDesc" />
      <el-table-column label="服务简介" align="center" prop="supplierServiceDetailText" />
      <el-table-column label="服务简介图片" align="center" prop="supplierServiceDetailIcon" >
        <template slot-scope="scope">
          <el-image :src="scope.row.supplierServiceDetailIcon" :preview-src-list="[scope.row.supplierServiceDetailIcon]" style="width: 50px;max-height: 150px;"/>
        </template>
      </el-table-column>
      <el-table-column label="单位服务时长" align="center" prop="serveUnitTime" />
      <el-table-column label="单位可服务人数" align="center" prop="serveUnitSupportNum" />
      <el-table-column label="创建者账号" align="center" prop="createBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['console:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['console:info:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-date"
            @click="handleSchedule(scope.row)"
            v-hasPermi="['console:info:edit']"
          >排班</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户信息对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="600px" append-to-body class="supplierInfoDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" type="textarea" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="供应商图片" prop="supplierPic">
          <el-input v-model="form.supplierPic" type="text" placeholder="请上传供应商照片" disabled />
          <ImageEdit @changeImage="changeImage" :value="form.supplierPic" :limit="1"></ImageEdit>
        </el-form-item>
        <el-form-item label="供应商类别" prop="serviceId">
          <el-select v-model="form.serviceId" placeholder="请选择供应商类别" clearable>
            <el-option
              v-for="(label, key) in serviceMap"
              :key="key"
              :label="label"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商详细地址" prop="supplierDetailAddress">
          <el-input v-model="form.supplierDetailAddress" type="textarea" placeholder="请输入供应商详细地址" />
        </el-form-item>
        <el-form-item label="供应商详情" prop="supplierDesc">
          <el-input v-model="form.supplierDesc" type="textarea" placeholder="请输入供应商详情" />
        </el-form-item>

        <el-form-item label="服务简介" prop="supplierServiceDetailText">
          <el-input v-model="form.supplierServiceDetailText" type="textarea" placeholder="请输入服务简介" />
        </el-form-item>
        <el-form-item label="服务简介图片" prop="supplierServiceDetailIcon">
          <el-input v-model="form.supplierServiceDetailIcon" type="text" placeholder="请上传服务简介图片" disabled />
          <ImageEdit @changeImage="changeImage($event,'supplierServiceDetailIcon')" :value="form.supplierServiceDetailIcon" :limit="1"></ImageEdit>
        </el-form-item>
        <el-form-item label="单位服务时长" prop="serveUnitTime">
          <el-input v-model="form.serveUnitTime" type="number" placeholder="请输入单位服务时长">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="单位可服务人数" prop="serveUnitSupportNum">
          <el-input v-model="form.serveUnitSupportNum" type="number" placeholder="请输入单位可服务人数" />
        </el-form-item>
        <el-form-item label="创建者账号" prop="createBy">
          <el-input v-model="form.createBy" type="textarea" placeholder="请输入创建者账号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加员工排班 -->
    <el-dialog  :close-on-click-modal="false" title="添加员工排班" :visible.sync="openSchedule" width="600px" append-to-body  class="scheduleDialog">
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="80px">
        <el-row>
          <el-form-item label="服务场所" prop="buildingId">
            <el-select v-model="form2.buildingId" placeholder="请选择服务场所" clearable>
              <el-option
                v-for="(label, key) in buildingMap"
                :key="key"
                :label="label"
                :value="key"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5" class="serveDay">
          <el-form-item label="服务日期" prop="serveStartDay">
            <el-date-picker
              v-model="form2.serveStartDay"
              type="date"
              :picker-options="{
                disabledDate:pickerOptionsStartDisabledDate}"
              placeholder="服务开始日期">
            </el-date-picker>
          </el-form-item>
          <span style="text-align: center;line-height: 32px;margin: 0 3px;">-</span>
          <el-form-item label="" prop="serveEndDay" label-width="0">
            <el-date-picker
              v-model="form2.serveEndDay"
              type="date"
              :picker-options="{
                disabledDate:pickerOptionsEndDisabledDate
              }"
              placeholder="服务结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="appointWeeks" label-width="0">
            <el-select
              v-model="form2.appointWeeks"
              multiple
              collapse-tags
              placeholder="请选择服务周">
              <el-option
                v-for="item in appointWeeksOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="13">
            <el-form-item label="服务时间" prop="workStartTime">
              <el-time-select
                placeholder="起始时间"
                v-model="form2.workStartTime"
                :picker-options="{
                  start: '09:00',
                  step: '00:05',
                  end: '22:00',
                  maxTime: form2.sleepStartTime || form2.sleepEndTime || form2.workEndTime
                }">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="text-align: center;line-height: 32px;">-</el-col>
          <el-col :span="10">
            <el-form-item label="" prop="workEndTime" label-width="0">
              <el-time-select
                placeholder="结束时间"
                v-model="form2.workEndTime"
                :picker-options="{
                  start: '09:00',
                  step: '00:05',
                  end: '22:00',
                  minTime: form2.sleepEndTime || form2.sleepStartTime || form2.workStartTime
                }">
              </el-time-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="13">
            <el-form-item label="休息时间" prop="sleepStartTime">
              <el-time-select
                placeholder="起始时间"
                v-model="form2.sleepStartTime"
                :picker-options="{
                  start: '09:00',
                  step: '00:05',
                  end: '22:00',
                  minTime: form2.workStartTime,
                  maxTime: form2.sleepEndTime || form2.workEndTime
                }">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="text-align: center;line-height: 32px;">-</el-col>
          <el-col :span="10">
            <el-form-item label="" prop="sleepEndTime" label-width="0">
              <el-time-select
                placeholder="结束时间"
                v-model="form2.sleepEndTime"
                :picker-options="{
                  start: '09:00',
                  step: '00:05',
                  end: '22:00',
                  minTime: form2.sleepStartTime || form2.workStartTime,
                  maxTime: form2.workEndTime
                }">
              </el-time-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSchedule">确 定</el-button>
        <el-button @click="openSchedule = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, getDictMap, addSchedule } from "@/api/console/info";
import ImageEdit from "@/components/ImageEdit/Index";
import { parseTime } from '@/utils/ruoyi'

export default {
  name: "Info",
  components: { ImageEdit },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商户信息表格数据
      infoList: [],
      // 供应商类别
      serviceMap: {},
      // 服务场所
      buildingMap: {},
      // 供应商名称
      supplierNames: [],
      appointWeeksOption: [
        {label: '周一', value: 1},
        {label: '周二', value: 2},
        {label: '周三', value: 3},
        {label: '周四', value: 4},
        {label: '周五', value: 5}
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 排班弹出层
      openSchedule: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierName: null,
        supplierPic: null,
        score: null,
        serviceId: null,
        supplierDetailAddress: null,
        supplierDesc: null,
        supplierServiceDetailText: null,
        supplierServiceDetailIcon: null,
        serveUnitTime: null,
        serveUnitSupportNum: null
      },
      // 表单参数
      form: {},
      // 添加员工排版
      form2: {
        buildingId: '',
        serveStartDay: '',
        serveEndDay: '',
        appointWeeks: '',
        workStartTime: '',
        workEndTime: '',
        sleepStartTime: '',
        sleepEndTime: '',
      },
      // 表单校验
      rules: {
        supplierName: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" }
        ],
        supplierPic: [
          { required: true, message: "供应商图片不能为空", trigger: "blur" }
        ],
        score: [
          { required: true, message: "供应商评分不能为空", trigger: "blur" }
        ],
        serviceId: [
          { required: true, message: "供应商类别不能为空", trigger: "change" }
        ],
        // supplierDetailAddress: [
        //   { required: true, message: "供应商详细地址不能为空", trigger: "blur" }
        // ],
        // supplierDesc: [
        //   { required: true, message: "供应商详情不能为空", trigger: "blur" }
        // ],
        // supplierServiceDetailText: [
        //   { required: true, message: "服务简介不能为空", trigger: "blur" }
        // ],
        // supplierServiceDetailIcon: [
        //   { required: true, message: "服务简介图片不能为空", trigger: "blur" }
        // ],
        serveUnitTime: [
          { required: true, message: "单位服务时长不能为空", trigger: "blur" }
        ],
        serveUnitSupportNum: [
          { required: true, message: "单位可服务人数不能为空", trigger: "blur" }
        ],
      },
      rules2: {
        buildingId:[
          { required: true, message: "请选择服务场所", trigger: "blur" }
        ],
        serveStartDay:[
          { required: true, message: "请选择服务开始日期", trigger: "blur" }
        ],
        serveEndDay:[
          { required: true, message: "请选择服务结束日期", trigger: "blur" }
        ],
        appointWeeks:[
          { required: true, message: "请选择服务周", trigger: "blur" }
        ],
        workStartTime:[
          { required: true, message: "请选择服务开始时间", trigger: "blur" }
        ],
        workEndTime:[
          { required: true, message: "请选择服务结束时间", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getDictMap();
    this.getList();
  },
  methods: {
    pickerOptionsStartDisabledDate(val){
      if (this.form2.serveEndDay) {
        return new Date(val).getTime() < new Date().getTime() - 24 *3600* 1000
          ||  new Date(val).getTime() > new Date(this.form2.serveEndDay).getTime()
      } else {
        return new Date(val).getTime() < new Date().getTime() - 24 *3600* 1000
      }
    },
    pickerOptionsEndDisabledDate(val) {
      if (this.form2.serveStartDay) {
        return new Date(val).getTime() < new Date().getTime() - 24 *3600* 1000
          ||  new Date(val).getTime() < new Date(this.form2.serveStartDay).getTime()
      } else {
        return new Date(val).getTime() < new Date().getTime() - 24 *3600* 1000
      }
    },
    changeImage($event,type) {
      if(type == 'supplierServiceDetailIcon') {
        this.form.supplierServiceDetailIcon = $event;
      } else{
        this.form.supplierPic = $event;
      }
    },
    /** 查询商户信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        supplierName: null,
        supplierPic: null,
        score: null,
        serviceId: null,
        supplierDetailAddress: null,
        supplierDesc: null,
        supplierServiceDetailText: null,
        supplierServiceDetailIcon: null,
        serveUnitTime: null,
        serveUnitSupportNum: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 客服务地址 */
    getDictMap() {
      getDictMap({}).then(response => {
        this.serviceMap = (response.data || {}).serviceMap || {};
        this.buildingMap = (response.data || {}).buildingMap || {};
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.supplierNames = selection.map(item => item.supplierName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.form.serviceId = String(this.form.serviceId);
        this.open = true;
        this.title = "修改商户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.supplierName || this.supplierNames
      this.$modal.confirm('是否确认删除供应商名称为"' + names + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('console/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    /** 排班按钮操作 */
    handleSchedule(row) {
      this.form2 = {};
      this.form2.serveUnitSupportNum = row.serveUnitSupportNum;
      this.form2.serveUnitTime = row.serveUnitTime;
      this.form2.id = row.id;
      this.form2.pid = row.pid;
      this.openSchedule = true;
    },
    submitSchedule() {
      this.$refs["form2"].validate(valid => {
        let params = {...this.form2}
        params.serveDays = [];
        let currentDay = this.form2.serveStartDay;
        const endDay = this.form2.serveEndDay;
        while(endDay.getTime() >= currentDay.getTime()) {
          params.serveDays.push(parseTime(currentDay, "{y}-{m}-{d}"));
          currentDay = new Date(currentDay.getTime() + 86400000);
        }
        delete params.serveStartDay
        delete params.serveEndDay
        if (!params.sleepStartTime || !params.sleepEndTime){
          params.sleepStartTime = params.workStartTime
          params.sleepEndTime = params.workStartTime
        }
        if (valid) {
          addSchedule(params).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.openSchedule = false;
          });
        }
      });
    }
  }
};
</script>
<style lang="scss">
  .supplierInfoDialog{
    .el-upload-list--picture-card .el-upload-list__item{
      height: auto;
      max-height: 300px;
    }
    .el-upload-list--picture-card .el-upload-list__item-thumbnail{
      height: auto;
    }
  }
  .scheduleDialog{
    .serveDay{
      .el-form-item{
        display: inline-block;
      }
      .el-date-editor.el-input, .el-date-editor.el-input__inner{
        width: 150px;
      }
      .el-select > .el-input{
        width: 150px;
        margin-left: 10px;
      }
    }
  }
</style>
